package models.sys;

import play.db.jpa.JPABase;

import javax.persistence.Entity;
import javax.persistence.Table;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by adinlead on 2016-05-26-0026.
 */
@Entity
@Table(name="tb_admin_user_log")
public class AdminUserLog extends SystemModel {
    public static final int TYPE_LOGIN = 1;    //登录记录类型日志
    public static final int TYPE_ACTION = 2;   //操作记录类型日志

    private AdminUserLog(Integer logtype) {
        this.logtype = logtype;
        this.logtime = new Date();
    }

    /**
     * @function 产生一个类型为登录记录的日志
     * @return
     */
    public static AdminUserLog getLoginLog(){
        return new AdminUserLog(TYPE_LOGIN);
    }

    /**
     * @function 产生一个类型为登录记录的日志
     * @return
     */
    public static AdminUserLog getActionLog(){
        return new AdminUserLog(TYPE_ACTION);
    }

    public Integer logtype; //日志类型(0:登录日志,1:操作日志)
    public String logip;  //登录IP
    public Date logtime;  //登陆时间
    public Boolean issuccess; //登录是否成功
    /**********/
    public String target;   //请求目标
    public String menuname; //模块名称(如果访问的目标为模块的话)
    /**********/
    public String logname;    //登录名
    public Long userid;    //用户ID

    public String toLoggerString() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        switch (logtype) {
            case TYPE_LOGIN: {
                String status = "失败";
                if (issuccess) {
                    status = "成功";
                    status += "\tuserid:" + userid;
                }
                return "后台用户登录\t" + logname + "\t" + logip + "\t" + format.format(logtime) + "\t" + status;
            }
            case TYPE_ACTION: {
                String status = "拒绝访问";
                if (issuccess) {
                    status = "允许访问";
                }
                return "后台用户访问接口\t" + logname + "\t" + logip + "\t" + format.format(logtime) + "\t" + target + "\t" + (menuname == null ? "" : menuname) + "\t" + status;
            }
            default:
                return null;
        }
    }

    /**
     * store (ie insert) the entity.
     */
    @Override
    public <T extends JPABase> T save() {
        if(logtype == TYPE_LOGIN) {
            super._save();
            return (T) this;
        }else {
            return (T) this;
        }
    }

}
